package com.agent.common.handler;

import com.agent.common.entity.UserContext;
import com.agent.common.exception.AuthenticationException;
import com.agent.common.result.ResultCode;
import com.agent.common.utils.JwtUtils;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;

/**
 * 统一JWT认证处理器
 */
public class JwtAuthHandler {
    
    private static final String AUTH_HEADER = "Authorization";
    private static final String BEARER_PREFIX = "Bearer ";
    
    private final JwtUtils jwtUtils;

    public JwtAuthHandler(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    /**
     * 统一认证方法
     */
    public UserContext authenticate(HttpServletRequest request) {
        String token = extractToken(request);
        validateToken(token);
        return extractUserContext(token);
    }

    /**
     * 提取令牌
     */
    public String extractToken(HttpServletRequest request) {
        String authHeader = request.getHeader(AUTH_HEADER);
        if (!StringUtils.hasText(authHeader) || !authHeader.startsWith(BEARER_PREFIX)) {
            throw new AuthenticationException(ResultCode.UNAUTHORIZED, "Missing or invalid Authorization header");
        }
        return authHeader.substring(BEARER_PREFIX.length());
    }

    /**
     * 验证令牌有效性
     */
    public void validateToken(String token) {
        if (!jwtUtils.validateRsaToken(token)) {
            throw new AuthenticationException(ResultCode.UNAUTHORIZED, "Invalid or expired token");
        }
    }

    /**
     * 提取用户上下文
     */
    public UserContext extractUserContext(String token) {
        UserContext userContext = jwtUtils.extractUserContext(token, true);
        if (userContext == null) {
            throw new AuthenticationException(ResultCode.USER_NOT_EXIST, "User context not found");
        }
        return userContext;
    }
}